package com.tianji.aigc.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.aigc.config.SessionProperties;
import com.tianji.aigc.domain.pojo.ChatSession;
import com.tianji.aigc.domain.vo.SessionVO;
import com.tianji.aigc.mapper.ChatSessionMapper;
import com.tianji.aigc.service.ChatSessionService;
import com.tianji.common.utils.RandomUtils;
import com.tianji.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class ChatSessionServiceImpl extends ServiceImpl<ChatSessionMapper, ChatSession> implements ChatSessionService {

    @Autowired
    private SessionProperties sessionProperties;

    /**
     * 创建会话session
     *
     * @param n 热门问题的数量
     * @return 会话信息
     */
    @Override
    public SessionVO createSession(Integer n) {
        //新增+保存
        //1.保存到数据库
        //随机生成会话Id(sessionId)
        String sessionId = IdUtil.fastSimpleUUID();
        log.info("随机生成会话Id:{}", sessionId);
        Long userId = UserContext.getUser();
        log.info("用户Id:{}", userId);
        //这里面标题先不存,标题是根据第一次对话总结的,刚开始没有就不写
        ChatSession build = ChatSession.builder()
                .sessionId(sessionId)
                .userId(userId)
                .build();
        this.save(build);

        //2.查询数据 返给前端呈现的随机三个热点问题
        SessionVO bean = BeanUtil.toBean(sessionProperties, SessionVO.class);
        //设置sessionId 是因为bean里面没有这个属性
        bean.setSessionId(sessionId);
        log.info("返还给前端SessionVO里的sessionId为:{}", bean.getSessionId());
        List<SessionVO.Example> examples = RandomUtil.randomEleList(bean.getExamples(), n);
        bean.setExamples(examples);
        return bean;
    }

    /**
     * 热门话题
     */
    @Override
    public List<SessionVO.Example> hot(Integer n) {
        List<SessionVO.Example> examples = sessionProperties.getExamples();
        return RandomUtils.randomEleList(examples,n);
    }
}